package com.cwt_taxi_xa;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Handler;

import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.model.ContactInfo;
import com.cwt_taxi_xa.protocol.DispatchCenterUsers;
import com.cwt_taxi_xa.protocol.MCUUtil;
import com.cwt_taxi_xa.service.DvrService;
import com.cwt_taxi_xa.service.DvrTCService;
import com.cwt_taxi_xa.service.FloatService;
import com.cwt_taxi_xa.service.SerialPortService;
import com.cwt_taxi_xa.timer.ThreanReTime;
import com.cwt_taxi_xa.timer.TimerCommon;
import com.cwt_taxi_xa.util.AppBiz;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.ExceptionUtil;
import com.cwt_taxi_xa.util.GPSUpdataUtil;
import com.cwt_taxi_xa.util.GPSUtil;
import com.cwt_taxi_xa.util.SPUtils;
import com.cwt_taxi_xa.util.TTsFunction;

import org.litepal.LitePalApplication;

import java.io.File;
import java.util.ArrayList;
import java.util.Timer;

public class MainApplication extends LitePalApplication {

	//本来放在通用timer里，因为那个定时器在dvr网络异常时总会停止，然后被重启，所以放到此处
	public static boolean firstviv = true;

	//原来每次心跳后设置顶灯状态，现在改成只在程序启动后设置3次
	public static int setDDStatus = 3;



	MediaPlayer mMediaPlayer = null;

	public static MainApplication instance;
	public static CWTBaseActivity topActivity;
	public ArrayList<ContactInfo> infos;
	/**
	 * 初始化音量文件、按键声音文件加载
	 */
	public static SoundPool sp = null;
	public static int music = 0;



	// 获取本地application的对象
	public static MainApplication getInstance() {
		if (instance ==  null) {
			instance = new MainApplication();
		}
		return instance;
	}

	// 异常捕获
	private CrashHandler crashHandler;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		instance = this;

		crashHandler = new CrashHandler(getApplicationContext());
		Thread.setDefaultUncaughtExceptionHandler(crashHandler);

		//判断哪家dvr，郑工的要发广播
		if(SPUtils.getParamInteger(SPConstants.SPK_dvr, SPConstants.SPV_dvr)==2){
			sendBroadcast(new Intent("android.yho.intent.set.ethernet.ip"));
		}


		Constants.PORT_PROTECT = SPUtils.getParamBoolean("xaiplock", true);


		// 初始化TTS


		try {
			TTsFunction.initTTS();
		} catch (Exception e) {
			e.printStackTrace();
			AppLog.e("TTS初始化失败");
		}

		GPSUtil gu = GPSUtil.getInstance();

		// 注册网络监听---改在通用timer主动监测
//		IntentFilter netfilter = new IntentFilter();
//		NetworkReceiver networkReceiver = new NetworkReceiver();
//		netfilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//		registerReceiver(networkReceiver, netfilter);

		// U盘接收器
//		UsbStatesReceiver usbStatesReceiver = new UsbStatesReceiver();
//		IntentFilter usbfilter = new IntentFilter();
//		usbfilter.addAction(Intent.ACTION_MEDIA_CHECKING);
//		usbfilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
//		usbfilter.addAction(Intent.ACTION_MEDIA_EJECT);
//		usbfilter.addAction(Intent.ACTION_MEDIA_REMOVED);
//		registerReceiver(usbStatesReceiver, usbfilter);

		// 初始化串口
		startService(new Intent(this, SerialPortService.class));

		// 初始化dvr透传服务
		startService(new Intent(this, DvrService.class));
		startService(new Intent(this, DvrTCService.class));

		// 初始化悬浮窗
		startService(new Intent(this, FloatService.class));


		//启动平台连接线程
		DispatchCenterUsers.startTimerConnectSvr();

		//通用线程，每秒刷新
		mTimerCom = new TimerCommon();
		mtimer = new Timer();
		mtimer.schedule(mTimerCom, 1000, 1000);
//		new Timer().schedule(new TimerCommon(), 1000, 1000);
//		new Timer().schedule(new TimerCommonReTime(), 1000, 1000);
		new Thread(new ThreanReTime()).start();
		//初始化音量文件、按键声音文件加载
		sp = new SoundPool(10,AudioManager.STREAM_NOTIFICATION, 0);
		music = sp.load(this,R.raw.dong, 1); // 把你的声音素材放到res/raw里，第2个参数即为资源文件，第3个为音乐的优先级


		// 启动心跳维持连接
		DispatchCenterUsers.startHeartBeat();
		DispatchCenterUsers.socketManager.create();
		// 初始化定位
		gu.init();

		//第三次重写背景声音规则
		AppLog.savelog("声音忽大忽小问题：------------1");
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					if(true){
						//return;
					}
					Thread.sleep(5000);
					for (int j = 0; j < 10; j++) {
						AppLog.savelog("声音忽大忽小问题：------------2");
						try {
							mMediaPlayer = MediaPlayer.create(MainApplication.this, R.raw.testbg);
							AppLog.savelog("声音忽大忽小问题：------------3");
						} catch (Exception e) {
							e.printStackTrace();
						}
						if(mMediaPlayer!=null){
							break;
						}
					}
					mMediaPlayer.setLooping(true);
					AppLog.savelog("声音忽大忽小问题：------------4");
					mMediaPlayer.start();
					AppLog.savelog("声音忽大忽小问题：------------5");
					try {
						Thread.sleep(15000);
						MCUUtil.hasVic(true);
						AppLog.savelog("声音忽大忽小问题：------------6");
						Thread.sleep(100);
						MCUUtil.setvol(SPUtils.getParamInteger(SPConstants.SPK_vol, SPConstants.SPV_vol), "初次播放背景空白音后恢复默认音量6");
						AppLog.savelog("声音忽大忽小问题：------------7");
						Thread.sleep(100);
						MCUUtil.selecterVic(2);
						AppLog.savelog("声音忽大忽小问题：------------8");
						MainApplication.topActivity.myToast("功放初始化成功");
						AppLog.savelog("声音忽大忽小问题：------------9");
					} catch (Exception e) {
						AppLog.savelog("声音忽大忽小问题：------------10\n"+CrashHandler.exception(e));
					}
				} catch (Exception e) {
					AppLog.savelog("声音忽大忽小问题：------------11\n"+CrashHandler.exception(e));
				}
			}
		}).start();


		checkDIDA();


		if(!SPUtils.getParamBoolean("gpsupdata", false)){
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(10000);

						final GPSUpdataUtil util = new GPSUpdataUtil();
						util.initGpsUpdata(new GPSUpdataUtil.onGPSUpdata() {
							@Override
							public void onInit() {
								AppLog.e("GPS升级封装测试-onInit");
								util.check();
							}

							@Override
							public void onUpdata(int percent) {
								AppLog.e("升级封装测试-onUpdata："+percent);
							}

							@Override
							public void onSucceed() {
								SPUtils.setParam("gpsupdata",true);
								AppLog.e("GPS升级封装测试-onSucceed");
							}

							@Override
							public void onCheck(String version) {
								version = version.replace("V","");
								version = version.replace(".","");
								int vi = Integer.parseInt(version);
								AppLog.e("GPS升级封装测试-v:"+vi);
//								if(vi<=5300){
								if(vi<5300){
									AppLog.e("GPS升级封装测试-版本低于5300，开始升级:");
									MainApplication.topActivity.myToast("GPS模块升级");
									util.upDate();
								}else{
									AppLog.e("GPS升级封装测试-新版本，取消升级");
									util.restartAndclose();
								}
							}

							@Override
							public void onFailure() {
								SPUtils.setParam("gpsupdata",true);
								TTsFunction.speakText("GPS升级重启");
								try {
									Intent intent = new Intent(
											"android.intent.action.ACTION_REQUEST_SHUTDOWN");
									intent.putExtra("android.intent.extra.KEY_CONFIRM", false);
									// 其中false换成true,会弹出是否关机的确认窗口
									intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
									MainApplication.getInstance().startActivity(intent);

								} catch (Exception ex) {
									ex.printStackTrace();
								}
							}
						});
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}).start();
		}


//		new Thread(new Runnable() {
//			@Override
//			public void run() {
//				ShellUtils.execCommand("rm -rf /system/priv-app/Launcher_zhu_7.6.apk",true);
//			}
//		}).start();
	}


	private void checkDIDA() {
		boolean install = false;
		String pkgName = "com.didachuxing.taxi.terminaldevice";
		try {
			@SuppressLint("WrongConstant") PackageInfo info = getPackageManager().getPackageInfo(pkgName, 1);
			if (info != null && info.activities.length > 0) {
				install = true;
			} else {
				install = false;
			}
			AppLog.i("包名: " + pkgName + "; 是否安装: " + install);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e));
		}



		if(install){
			boolean launch = SPUtils.getParamBoolean("launchAppdida", false);
			if(!launch){
				new AppBiz(this).launchApp("com.didachuxing.taxi.terminaldevice");
				SPUtils.setParam("launchAppdida", true);
			}
		}else{
			SPUtils.setParam("launchAppdida", false);
		}
	}

	boolean delFile(String filename) {
		File file = new File(filename);
		if (!file.exists()) {
			return false;
		}

		if (file.isFile()) {
			return file.delete();
		} else {
			String[] filenames = file.list();
			for (String f : filenames) {
				delFile(f);
			}
			return file.delete();
		}
	}
	public TimerCommon mTimerCom;
	public Timer mtimer;



	public static Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {

		}
	};

}
